/*
 *@author: YangJie
 *@date: 2021-04-09 10:49:49
 *@version:
 *@description: 参数设置->公共配置->班组
 */
import React, { Component } from 'react';
import { Table,  Form, Card, Tabs,  Row, Col,  Radio, DatePicker, Popover, Divider } from 'antd';
import '@/assets/css/settings';
import BasicForm from '../../components_yyr/common/basicFormbaobiao';
import { FileDown } from '../../components_yyr/commponent/File';
import Paging from '../../components_yyr/commponent/Paging';
import DepartmentAnalyse1_sort from './departmentAnalyse/departmentAnalyse1_sort';
import DepartmentAnalyse2_equType from './departmentAnalyse/departmentAnalyse2_equType';
import DepartmentAnalyse3_details from './departmentAnalyse/departmentAnalyse3_details';
import DepartmentAnalyse4_errorList from './departmentAnalyse/departmentAnalyse4_errorList';
import DepartmentAnalyse5_recordDetails from './departmentAnalyse/departmentAnalyse5_recordDetails';
import DepartmentAnalyse6_recordDetails from './departmentAnalyse/departmentAnalyse6_recordDetails';
import Echarts from 'echarts-for-react';
// import 'echarts-gl';
import { euqApplicationName_gl, lotAuth, lotAuth2 } from '../../config';
import { euqApplicationName } from '../../config';

var date = new Date();
let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
let year = date.getFullYear()
let todayEnd = `${year}-${month}-${day} 23:59:59`
let todayStart = `${year}-${month}-01 00:00:00`
const { TabPane } = Tabs;
const {  RangePicker, } = DatePicker
class departmentAnalyse extends Component {

    state = {
        loading: false, //加载中...
        dataSource: [], //数据源
        drawerVisible: false, //新增修改抽屉的显示与隐藏
        chooseData: {}, //用checkbox选择好的数据
        total: 0, //总数据量
        formValues: {},
        weekList: [],
        value: '1',
        //  activeKey:'top',
        activeKey: 'top',
        panes: [],
        newTabIndex: 0,
        equipmentTypeChart: [],
        thisMonth: [], lastMonth: [], last90Day: [] ,dateString:[] ,DepartmentList:[] ,EquTypeList:[]
    };
    constructor(props) {
        super(props);
        // console.log(props);
    }
    componentDidMount() {
        this.getDate()
        this.fetch({
            pageNum: 1,
            pageSize: 10,
            // startTime:todayStart,
            // endTime:todayEnd,
            timeList: [todayStart, todayEnd]
        });
        this.queryTreeDepartment()
        this.findEquTypePageList()
    }
    //初始化加载数据
    fetch = (data) => {
        let option1 = this.option1
        let option2 = this.option2
        let str = ''
        console.log(data)
        if (data.timeList && data.timeList.length === 2) {
            data['startTime'] = data.timeList[0]
            data['endTime'] = data.timeList[1]
            // str += '&startTime=' + data.timeList[0] + '&endTime=' + data.timeList[1]
            delete data['timeList']
        }else if(!data.timeList || data.timeList.length===0){
            data['startTime'] = data['startTime'] ? data['startTime'] : ''
            data['endTime'] = data['endTime'] ? data['endTime'] : ''
            delete data['timeList']
        }
        this.setState({ loading: true, formValues: data},()=>{
            console.log(this.state.formValues)
        })
        for (var key in data) {
            if (data[key] || data[key] == 0) {
                str += `&${key}=${data[key]}`
            }
        }
        this.get(`${euqApplicationName_gl}/equipmentDeptReport/findEquipmentDeptChart?${str}`).then(res => {
            let arr = res.data
            option1.xAxis[0].data = arr.map(item => item.deptName)
            option1.series[0].data = arr.map(item => item.faultTotal)
            option1.series[1].data = arr.map(item => item.hours)
            option2.xAxis[0].data = arr.map(item => item.deptName)
            option2.series[0].data = arr.map(item => item.stops)
            option2.series[1].data = arr.map(item => item.tjHours)
            this.setState({ equipmentTypeChart: arr }, () => {
                this.echartRef1.getEchartsInstance().setOption(option1, true);
                this.echartRef2.getEchartsInstance().setOption(option2, true);
            })
        })
        this.get(`${euqApplicationName_gl}/equipmentDeptReport/findEquipmentDeptTable?` + str).then(res => {
            console.log(res.data.data)
            this.setState({
                loading: false,
                dataSource: res.data.data,
                total: res.data.total,
            });
        })
    }
    queryTreeDepartment = () => {
        // this.get(`${lotAuth}/department/queryTreeDepartment`).then(res => {
        this.get(`${lotAuth2}/department/queryTreeDepartment`).then(res => {
			this.setState({
				DepartmentList : res.data
			});
		})
	}

    findEquTypePageList = () => {
		this.setState({ loading: true })
		this.get(euqApplicationName + '/parameter_setting_equipmentType/findEquTypePageList').then(res => {
		this.setState({
            EquTypeList: res.data,
			});
		})
    }; 
    getDate = () => {
        var date = new Date();
        let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
        let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
        let year = date.getFullYear()
        let todayEnd = `${year}-${month}-${day} 23:59:59`
        let todayStart = `${year}-${month}-01 00:00:00`
        let thisMonth = [todayStart, todayEnd]
        let lastMonth = this.getLastMonth()
        let last90Day = [this.getLast90Day(), todayEnd]
        this.setState({
            thisMonth, lastMonth, last90Day
        })
        // console.log(todayEnd,todayStart)
        // var dataList = [];
        // for (var i = 0; i < 3; i++) {
        //     var newDate = new Date(date);
        //     newDate.setMonth(date.getMonth() - i);
        //     dataList.unshift(`${newDate.getFullYear()}-${(newDate.getMonth() + 1).toString().padStart(2, '0')}`);
        // }
        // console.log(dataList)
        // console.log(this.getLastMonth())
        // console.log([this.getLast90Day(),todayEnd])
    }
    getLastMonth = () => {//获取上个月日期第一天
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() < 10 ? `0${nowDate.getMonth()}` : nowDate.getMonth();
        if (month == 0) {
            year = year - 1;
            month = 12;
        }
        var lastDay = new Date(year, month, 0);
        var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
        var yyyyMMdd = year + "-" + month + "-" + day + ' 23:59:59';
        return [year + "-" + month + "-01 00:00:00", yyyyMMdd];
    }
    /**
     * 获取上个月月底日期
     */
    getLast90Day = () => {
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() - 2 < 10 ? `0${nowDate.getMonth() - 2}` : nowDate.getMonth() - 2;
        if (month == 0) {
            month = 12;
            year = year - 1;
        }
        var lastDay = new Date(year, month, 0);
        var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
        var yyyyMMdd = year + "-" + month + "-" + day + ' 00:00:00';
        return yyyyMMdd;
    }
    getXianTiOption2 = () => {
        var colors = ['#5793f3', '#67e0e3'];
        const option = {
            color: colors,
            title:{
                text:'导出图片',
                show:false
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            grid: {
                right: '2%',
                left: '2%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    // dataView: {show: true, readOnly: false},
                    // restore: {show: true},
                    saveAsImage: { show: true, title: '导出图' }
                }
            },
            legend: {
                data: ['停机次数', '总停机时长']
            },
            xAxis: [
                {
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: []
                }
            ],
            yAxis: [
                // {
                // 	type: 'value',
                // 	name: '数量（m³）',
                // 	nameLocation: 'end',
                // 	nameTextStyle: { fontWeight: 'bold' }
                // }
                {
                    type: 'value',
                    name: '单位（次）',
                    position: 'left',
                    axisLine: {
                        lineStyle: {
                            color: colors[0]
                        }
                    },
                    // axisLabel: {
                    //     formatter: '{value}'
                    // }
                },
                {
                    type: 'value',
                    name: '单位（h）',
                    position: 'right',
                    axisLine: {
                        lineStyle: {
                            color: colors[1]
                        }
                    },
                    // axisLabel: {
                    //     formatter: '单位（h）'
                    // }
                }
            ],
            series: [
                {
                    name: '停机次数',
                    type: 'bar',
                    yAxisIndex: 0,
                    barWidth: 50,
                    label: {
                        show: true,
                        position: 'top'
                    },
                    data: []
                },
                {
                    name: '总停机时长',
                    type: 'line',
                    yAxisIndex: 1,
                    label: {
                        show: true,
                    },
                    data: []
                }
            ],
            dataZoom: [
                {
                    type: 'inside',
                    show: true,
                    xAxisIndex: [0],
                    // 缩放的开始位置的百分比，0 - 100
                    start: 1,
                    // 缩放的结束位置的百分比，0 - 100
                    end: 100,
                    // 缩放的开始位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // startValue?: number,
                    // 缩放的结束位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // endValue?: number
                }
            ]
        };
        this.option2 = option
        return option;
    };
    getXianTiOption = () => {
        var colors = ['#5793f3', '#67e0e3'];
        const option = {
            title:{
                text:'导出图片',
                show:false
            },
            color: colors,
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            grid: {
                right: '2%',
                left: '2%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    // dataView: {show: true, readOnly: false},
                    // restore: {show: true},
                    saveAsImage: { show: true, title: '导出图' }
                }
            },
            legend: {
                data: ['故障次数','总维修用时']
            },
            xAxis: [
                {
                    type: 'category',
                    axisTick: {
                        alignWithLabel: true
                    },
                    data: []
                }
            ],
            yAxis: [
                {
                    // width: 100,
                    type: 'value',
                    name: '单位（次）',
                    // min: 0,
                    // max: 250,
                    position: 'left',
                    axisLine: {
                        lineStyle: {
                            color: colors[0]
                        }
                    },
                    // axisLabel: {
                    //     formatter: '{value}'
                    // }
                },
                {
                    type: 'value',
                    name: '单位（h）',
                    position: 'right',
                    axisLine: {
                        lineStyle: {
                            color: colors[1]
                        }
                    },
                    // axisLabel: {
                    //     formatter: '单位（h）'
                    // }
                }
            ],
            series: [
                {
                    name: '故障次数',
                    type: 'bar',
                    yAxisIndex: 0,
                    barWidth: 50,
                    label: {
                        show: true,
                        position: 'top'
                    },
                    data: []
                },
                // {
                //     name: '降水量',
                //     type: 'bar',
                //     yAxisIndex: 1,
                //     data: [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]
                // },
                {
                    name: '总维修用时',
                    type: 'line',
                    yAxisIndex: 1,
                    label: {
                        show: true,
                    },
                    data: []
                }
            ],
            dataZoom: [
                {
                    type: 'inside',
                    show: true,
                    xAxisIndex: [0],
                    // 缩放的开始位置的百分比，0 - 100
                    start: 1,
                    // 缩放的结束位置的百分比，0 - 100
                    end: 100,
                    // 缩放的开始位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // startValue?: number,
                    // 缩放的结束位置的数值，只有在工具栏的缩放行为的事件中存在。
                    // endValue?: number
                }
            ]
        };
        this.option1 = option
        return option;
    };
    handleSizeChange = (e) => {
        console.log(`${e.target.value}`);
        this.props.form.resetFields('dateString')
        let value = e.target.value
        let data = {...this.state.formValues}
        switch (value) {
            case '1': {
                data.timeList = this.state.thisMonth
                break;
            }
            case '2': {
                data.timeList = this.state.lastMonth
                break;
            }
            case '3': {
                data.timeList = this.state.last90Day
                break;
            }
            case '4': {
                data.timeList = ['','']
                break;
            }
        }
        this.setState({ value },()=>{
            this.fetch(data)
        })
    }
    onChange = (date, dateString) => {
        if(dateString.length===2&&dateString[0]!=''){
            this.setState({ value: null ,dateString})
            let data = {...this.state.formValues}
            data.timeList = [dateString[0]+' 00:00:00',dateString[1]+' 23:59:59']
            this.fetch(data)
            console.log(date, dateString);
        }else{
            this.setState({value:'1'})
            this.fetch({
                pageNum: 1,
                pageSize: 10,
                timeList: [todayStart, todayEnd]
            })
        }
    }


    onChangeTabs = activeKey => {
        console.log(activeKey)
        this.setState({ activeKey });
    };

    onEdit = (targetKey, action) => {
        this[action](targetKey);
    };

    add = (record, title, activeKey,isNext,data,valueOld) => {
        console.log(activeKey)
        const {formValues,value} = this.state
        let panes = this.state.panes;
        let sc = activeKey.split('_')[1]
        let content;
        switch (sc) {
            case 'nextSort': {
                content = (
                    <>
                        <DepartmentAnalyse1_sort record={record} onEvent={this.onTestEvent} value={valueOld ? valueOld : value} formValues={data ? data : formValues} isNext={isNext}/>
                    </>
                );
                break;
            }
            case 'equType': {
                content = (
                    <>
                        <DepartmentAnalyse2_equType record={record} onEvent={this.onTestEvent} value={valueOld ? valueOld : value}   formValues={data ? data : formValues} isNext={isNext}/>
                    </>
                );
                break;
            }
            case 'details': {
                content = (
                    <>
                        <DepartmentAnalyse3_details record={record} onEvent={this.onTestEvent} value={valueOld ? valueOld : value}  formValues={data ? data : formValues} isNext={isNext}/>
                    </>
                );
                break;
            }
            case 'errorList': {
                content = (
                    <>
                        <DepartmentAnalyse4_errorList record={record} onEvent={this.onTestEvent} value={valueOld ? valueOld : value}  formValues={data ? data : formValues} isNext={isNext}/>
                    </>
                );
                break;
            }
            case 'recordDetails': {
                if(record.statusId===1 || record.statusId===0){
                    content = (
                        <>
                            <DepartmentAnalyse6_recordDetails record={record} onEvent={this.onTestEvent} value={valueOld ? valueOld : value}  formValues={data ? data : formValues}  isNext={isNext}/>
                        </>
                    );
                }else if(record.statusId ===2){
                    content = (
                        <>
                            <DepartmentAnalyse5_recordDetails record={record} onEvent={this.onTestEvent} value={valueOld ? valueOld : value}  formValues={data ? data : formValues}  isNext={isNext}/>
                        </>
                    );
                }
                break;
            }
        }

        if (panes.length > 0) {
            const aa = panes.filter(pane => pane.key !== activeKey)
            if (aa.length < panes.length) {
                this.setState({ panes, activeKey });
            } else if (aa.length === panes.length) {
                panes.push({ title, content, key: activeKey });
                this.setState({ panes, activeKey });
            }
        } else if (panes.length === 0) {
            panes.push({ title, content, key: activeKey });
            this.setState({ panes, activeKey });
        }

    };

    remove = targetKey => {
        let { activeKey } = this.state;
        let lastIndex;
        this.state.panes.forEach((pane, i) => {
            if (pane.key === targetKey) {
                lastIndex = i - 1;
            }
        });
        const panes = this.state.panes.filter(pane => pane.key !== targetKey);
        if (panes.length && activeKey === targetKey) {
            if (lastIndex >= 0) {
                activeKey = panes[lastIndex].key;
            } else {
                activeKey = 'top';
            }
        }
        if (panes.length === 0) {
            activeKey = 'top';
        }
        this.setState({ panes, activeKey });
    };

    //表单查询
    filterSubmit = values => {
        console.log(values)
        let data = { ...this.state.formValues,...values }
        console.log(data)
        this.fetch(data);
    };
    //头部关键字查询部分
    formList = () => {
		const {  DepartmentList ,EquTypeList } = this.state;
        const formList = [{ type: "TREESELECT", label: "部门", field: "deptId", name: 'name', valueField: 'id', list: DepartmentList ,allowClear:true},{
            type: 'TREESELECT', label: '类型', field: 'equTypeId', 
            name: 'name', valueField: 'id', list:EquTypeList,allowClear:true
        },];
        return formList;
    };

    onTestEvent = (e) => {
        console.log(111)
        if (e.type === 'add') {
            this.add(e.data.record, e.data.title, e.data.activeKey,e.data.isNext,e.data.data,e.data.valueOld)
        }
        console.log(e);
    }

    render() {
        const { chooseData, dataSource, loading, total, formValues, value ,dateString } = this.state;
        const columns = [
            // { title: '序号', width: 100, dataIndex: 'id' },
            {
                title: '透视操作', width: 180,
                render: (text, record) => {
                    return <>
                        <span style={{display:record.isParent===1 ? 'inline-block' : 'none'}}><a href onClick={() => this.add(record, `${record.deptName}部门透视分析`, `${record.deptId}_nextSort`,1)}>下级分类</a><Divider type="vertical" /></span>
                        <span><a href onClick={() => this.add(record, `${record.deptName}类型透视分析`, `${record.deptId}_equType`,1)}>类型透视</a><Divider type="vertical" /></span>
                        <span><a href onClick={() => this.add(record, `${record.deptName}-设备详情`, `${record.deptId}_details`,1)}>设备详情</a></span>
                    </>
                },align:'center',
            },
            { title: '设备部门', width: 100, dataIndex: 'deptName' ,align:'center',},
            {
                title: () => {
                    return '总台数'
                }, width: 80, dataIndex: 'equipmentTotal',align:'center',
            },
            {
                title: () => { return <Popover content={'总故障次数：此类型下（包含下级设备）所有设备故障次数'}><span>总故障次数</span></Popover> }, width: 100, dataIndex: 'faultTotal', render: (text, record) => {
                    return <span><a href onClick={() => this.add(record, `${record.deptName}故障单`, `${record.deptId}_errorList`,1)} style={{ color: 'red' }}>{text}</a></span>
                },align:'center',
            },
            { title: () => { return <Popover content={'已维修故障：此类型下（包含下级设备）已完成维修故障次数'}><span>已维修故障</span></Popover> }, width: 100, dataIndex: 'flushTotal',align:'center', },
            { title: () => { return <Popover content={'此类型下（包含下级设备）未故障设备数/总设备数'}><span>完好率</span></Popover> }, width: 80, dataIndex: 'rate',render:(text)=>{
                return text+'%'
            } ,align:'center',},
            { title: () => { return <Popover content={'此类型下（包含下级设备）总故障次数/故障设备数'}><span>台次比</span></Popover> }, width: 80, dataIndex: 'ratio' ,align:'center',},
            {
                title: () => { return <Popover content={'所有设备在故障维修时的总停机时长/设备数|此类型下（包含下级设备）所有设备中最长停机时长'}><span>停机时长(h)<br />(平均/最长)</span></Popover> }, width: 100, dataIndex: 'avgHour', render: (text,record) => {
                    return record.avgHour + '/' + record.zcDowntime
                },align:'center',
            },
            { title: () => { return <Popover content={'所有设备在故障维修时的总停机时长'}><span>总停机时长(h)</span></Popover> }, width: 120, dataIndex: 'tjHours',align:'center', },
            {
                title: () => {
                    return <Popover content={'所有设备在故障维修时的总维修时长/设备数|此类型下（包含下级设备）所有设备中最长维修时长'}><span>维修用时(h)
                        <br />(平均/最长)</span></Popover>
                }, width: 100, dataIndex: 'avgWxHour', render: (text,record) => {
                    return record.avgWxHour+ '/' + record.zcMaintenanceTime
                },align:'center',
            },
            { title: () => { return <Popover content={'所有设备在故障维修时的总维修时长'}><span>总维修用时(h)</span></Popover> }, width: 120, dataIndex: 'wxHours',align:'center', },
            // { title: () => { return <Popover content={'所有设备维修费用总和/此类型下（包含下级设备）所有设备中最大维修费用'}><span>总维修费用(元)<br />(总额/最大)</span></Popover> }, width: 110, dataIndex: 'type2533',render:(record)=>{
            //     return record.avgWxHour+'/'+record.zcMaintenanceTime
            // } },
            { title: () => { return <Popover content={'所有设备维修时填写的费用（以维修结束为准）'}><span>维修费用(元)</span></Popover> }, width: 100, dataIndex: 'maintenanceCosts',align:'center', },

        ]
        return (
            <div className="shadow-radius">
                <Tabs hideAdd
                    onChange={this.onChangeTabs}
                    activeKey={this.state.activeKey}
                    type="editable-card"
                    onEdit={this.onEdit}>
                    <TabPane tab="设备部门透视分析" key="top" closable={false}>
                        <Card>
                            <BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={ref => (this.child = ref)} />
                        </Card>
                        <div>
                            <Tabs defaultActiveKey="1">
                                <TabPane tab="故障次数/总维修用时" key="1" forceRender>
                                    <div style={{ display: 'flex' }}>
                                        <Echarts
                                            option={this.getXianTiOption()}
                                            style={{ width: '100%', height: '460px' }}
                                            ref={(e) => { this.echartRef1 = e; }}
                                        />
                                    </div>
                                </TabPane>
                                <TabPane tab="停机次数/总停机时长" key="2" forceRender>
                                    <div style={{ display: 'flex' }}>
                                        <Echarts
                                            option={this.getXianTiOption2()}
                                            style={{ width: '100%', height: '460px' }}
                                            ref={(e) => { this.echartRef2 = e }}
                                        />
                                    </div>
                                </TabPane>
                            </Tabs>
                        </div>

                        <div>
                            <Row>
                                <Col span={20}>
                                    <p>
                                        <span>时间：</span>
                                        <Radio.Group onChange={this.handleSizeChange} buttonStyle="solid" value={value}>
                                            <Radio.Button value="1">本月</Radio.Button>
                                            <Radio.Button value="2">上月</Radio.Button>
                                            <Radio.Button value="3">90日</Radio.Button>
                                            <Radio.Button value="4">历史</Radio.Button>
                                        </Radio.Group>
                                        <Form style={{display:'inline-block'}}>
                                            <Form.Item>
                                            {this.props.form.getFieldDecorator('dateString', {
                                                    // initialValue:[]defaultValue={dateString.length===2?[moment(dateString[0], 'YYYY/MM/DD'), moment(dateString[1], 'YYYY/MM/DD')]:''} 
                                                    })(<RangePicker onChange={this.onChange} style={{ marginLeft: 25 }} placeholder={['开始时间', '结束时间']} />)}
                                            </Form.Item>
                                        </Form>
                                    </p>
                                </Col>
                                <Col style={{ float: 'right' }}><FileDown fileName="设备部门透视分析报表" buttonName="导出表" method="post" apiPath={`${euqApplicationName_gl}/equipmentDeptReport/importEquipmentDeptTable`} data={formValues} /></Col>
                            </Row>
                        </div>
                        <Table columns={columns} rowKey={(record, index) => record.deptId} dataSource={dataSource} pagination={false} loading={loading}  scroll={{ x: 'calc(700px + 50%)' }}/>
                        <Paging total={total} formValues={formValues} fetch={pager => this.fetch(pager)} />
                    </TabPane>
                    {this.state.panes.map(pane => (
                        <TabPane tab={pane.title} key={pane.key}>
                            {pane.content}
                        </TabPane>
                    ))}
                </Tabs>
            </div>
        );
    }
}
export default Form.create()(departmentAnalyse);
